const { src, dest } = require('gulp');
const fs = require('fs');
const path = require('path');
const del = require('del');
const scss = require('gulp-sass');
const notify = require('gulp-notify');
const plumber = require('gulp-plumber');
const cleanCSS = require('gulp-clean-css');
const autoprefixer = require('gulp-autoprefixer');
const rename = require('gulp-rename');
const pipeMiddle = require('./pipeMiddle');

const rootPath = path.join(__dirname, '../../');
const scssSrcPath = rootPath + '/src/styles'

// scss 解析
function goscss(themeName, space) {
    return new Promise((resolve, reject) => {
        let s = src(rootPath + '/chalk/index.scss')
            .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) // 解析错误提示
            .pipe(scss.sync())
        if (space) {
            s = s.pipe(pipeMiddle((content) => {
                return `.${themeName} { ${content} }; `
            })).pipe(scss.sync())
        }
        s.pipe(autoprefixer({ cascade: false }))
            .pipe(cleanCSS())
            .pipe(rename(function (path) {
                return Object.assign(path, {
                    basename: themeName,
                    dirname: path.dirname.replace('\\chalk', '')
                })
            }))
            .pipe(dest('dist/'))
            .on('end', () => {
                resolve()
            })
    })
}

// 执行编译
async function main(space) {
    await del(rootPath + '/dist')
    src(rootPath + '/chalk/fonts/*').pipe(dest(rootPath + '/dist/fonts'));
    let files = fs.readdirSync(scssSrcPath)
    let cssImport = ''
    for (let item of files) {
        let fileName = item.split('.')[0]
        if (item.endsWith('.scss')) {
            cssImport += `@import"${fileName}.css";\n`
            let newVarStr = fs.readFileSync(scssSrcPath + '/' + item).toString()
            fs.writeFileSync(rootPath + '/chalk/common/var.scss', newVarStr)
            // 编译scss
            await goscss(fileName, space)
            console.log(item, '-->>> item')
        }
    }
    fs.writeFileSync(rootPath + '/dist/index.css', cssImport)
}

module.exports = main